package com.jy.app.lib.net;

import android.content.Context;
import android.util.Log;

import com.jy.app.lib.application.BaseApplication;
import com.jy.app.lib.base.TokenConfig;
import com.jy.app.lib.cache.HttpCache;
import com.jy.app.lib.utils.DeviceUtil;
import com.jy.app.lib.utils.JsonUtil;
import com.jy.app.lib.utils.LogUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.MySSLSocketFactory;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.util.TextUtils;


/**
 * Http请求工具类
 * Created by jan on 2016/3/28.
 *
 * @version 1.1
 */
public class HttpUtil {

    public static final String TAG = "HttpUtil";
    public static final String HEADER_APP_ID = "appId";
    public static final String HEADER_TIMESTAMP = "timestamp";
    public static final String HEADER_CLIENT_VER = "clientVersion";
    public static final String HEADER_CLIENT_TYPE = "clientType";
    public static final String HEADER_TOKEN = "token";
    public static final String HEADER_SIGN = "sign";
    public static final String CONTENT_TYPE = "application/json";
    public static final String ENCODE = "utf-8";
    public static final int CONNECT_OUT_TIME = 10 * 1000;
    //是否支持https
    public static boolean IS_HTTPS = true;
    //是否打印数据日志
    public static final boolean ENABLE_LOG = true;
    /**
     * 应用ID
     */
    public static int appId = 1000100;
    /**
     * 安全秘钥
     */
    public static final String secretKey = "347ce1eb4f38425abb1a6f131a6f8de6";
    //通讯令牌
    public static String token = "";
    public static final String clientType = "android";
    private static TokenConfig mTokenConfig;
    protected static LinkedList<RequestHandle> requestList = new LinkedList<>();
    public static volatile RequestHandle mRequestHandle;
    protected Context mContext = null;
    protected static AsyncHttpClient asyncHttpClient = HttpUtil.getInstance();
    protected static SyncHttpClient syncHttpClient = new SyncHttpClient();
    private static HashMap<String, Object> headerMap = new HashMap<>();

    public static AsyncHttpClient getInstance() {
        synchronized (HttpUtil.class) {
            if (asyncHttpClient == null) {
                asyncHttpClient = new AsyncHttpClient(true, 80, 433);
                initHttpClient();
            }
            if (syncHttpClient == null) {
                syncHttpClient = new SyncHttpClient();
                initSycnHttpParams();
            }
            if (mTokenConfig == null) {
                mTokenConfig = new TokenConfig(BaseApplication.appContext);
            }
            return asyncHttpClient;
        }
    }

    static {
        initHttpClient();
    }

    public static <T> void httpGet(Context context, String url, String params, HttpResponseHandler<T> handler) {
        StringEntity entity = null;
        try {
            entity = new StringEntity(params, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logD("GET", url, params);
        asyncHttpClient.get(context, url, entity, CONTENT_TYPE, handler);
    }

    public static <T> void httpGet(Context context, String url, String params, AsyncHttpResponseHandler handler) {
        StringEntity entity = null;
        try {
            entity = new StringEntity(params, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logD("GET", url, params);
        asyncHttpClient.get(context, url, entity, CONTENT_TYPE, handler);
    }

    public static <T> void httpGet(Context context, String url, String params, JsonHttpHandler<T> handler) {
        StringEntity entity = null;
        try {
            entity = new StringEntity(params, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logD("GET", url, params);
        asyncHttpClient.get(context, url, entity, CONTENT_TYPE, handler);
    }


    public static <T> void httpGet(String url, RequestParams params, JsonResponseHttpHandler<T> handler) {
        logD("GET", url, params.toString());
        RequestHandle requestHandle = asyncHttpClient.get(url, params, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void httpPut(Context context, String url, String params, AsyncHttpResponseHandler handler) {
        StringEntity entity = null;
        try {
            entity = new StringEntity(params, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logD("GET", url, params);
        asyncHttpClient.put(context, url, entity, CONTENT_TYPE, handler);
    }

    public static <T> void httpGet(String url, RequestParams params, HttpResponseHandler<T> handler) {
        String request = JsonUtil.toJson(params);
        logD("GET", url, params.toString());
        RequestHandle requestHandle = asyncHttpClient.get(url, params, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void httpGet(String url, RequestParams params, AsyncHttpResponseHandler handler) {
        logD("GET", url, JsonUtil.toJson(params));
        RequestHandle requestHandle = asyncHttpClient.get(url, params, handler);
        mRequestHandle = requestHandle;
    }

    /**
     * 初始化异步请求的相关信息
     */
    private static void initHttpClient() {
        if (headerMap == null) {
            headerMap = new HashMap<>();
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String clientVersion = DeviceUtil.getVersionName(BaseApplication.appContext);
        headerMap.put(HEADER_APP_ID, String.valueOf(appId));
        headerMap.put(HEADER_TIMESTAMP, timestamp);
        headerMap.put(HEADER_CLIENT_TYPE, clientType);
        headerMap.put(HEADER_CLIENT_VER, clientVersion);
        asyncHttpClient.setConnectTimeout(CONNECT_OUT_TIME);
        asyncHttpClient.setTimeout(CONNECT_OUT_TIME);
        initHeaderInfo();
        if (!TextUtils.isEmpty(token)) {
            LogUtil.i("initHttpClient->token=" + token);
            asyncHttpClient.addHeader(HEADER_TOKEN, token);
        }
        if (IS_HTTPS)
            try {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
                MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
                sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                asyncHttpClient.setSSLSocketFactory(sf);
            } catch (Exception e) {

            }
//        asyncHttpClient.addHeader("sign", getToken(timestamp, clientType, null));
    }

    /**
     * 添加头信息
     *
     * @param key
     * @param value
     */
    public static void addHeader(String key, String value) {
        addHeader(key, value, false);
    }

    /**
     * 添加头信息
     *
     * @param key
     * @param value
     */
    public static void addHeader(String key, String value, boolean isLocal) {
        if (android.text.TextUtils.isEmpty(key)) {
            return;
        }
        if (isLocal) {
            headerMap.put(key, value);
        }
        if (asyncHttpClient != null) {
            asyncHttpClient.addHeader(key, value);
        }
    }

    /**
     * 清除所有的header
     */
    public static void cleanHeader() {
        headerMap.clear();
        initHttpClient();
    }

    public void setToken(String token) {
        if (!TextUtils.isEmpty(token)) {
            mTokenConfig.setToken(token);
            asyncHttpClient.addHeader(HEADER_TOKEN, token);
        }
    }

    public static void setAsyncHttpHeaders(Map<String, Object> paramsMap) {
        if (paramsMap == null) {
            paramsMap = new HashMap<>();
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String clientVersion = DeviceUtil.getVersionName(BaseApplication.appContext);
        asyncHttpClient.setConnectTimeout(CONNECT_OUT_TIME);
        asyncHttpClient.setTimeout(CONNECT_OUT_TIME);
        if (!paramsMap.containsKey("isToken")) {
            mTokenConfig = new TokenConfig(BaseApplication.appContext);
            token = mTokenConfig.getToken();
            asyncHttpClient.addHeader(HEADER_TOKEN, token);
            LogUtil.i("setAsyncHttpHeaders->token=" + token);
            paramsMap.remove("isToken");
        }
        asyncHttpClient.addHeader(HEADER_SIGN, getToken(timestamp, clientType, paramsMap));
        initHeaderInfo();
    }

    private static String getToken(String timestamp, String clientType, Map<String, Object> paramsMap) {
//        String token =appId+":"+timestamp+":"+clientType+":"+clientVersion+":"+secretKey;
//        return Base64.encodeToString(MD5Utils.MD5(MD5Utils.MD5(token)).getBytes(),Base64.NO_WRAP);
        return AppSignUtil.getSign(appId, timestamp, clientType, paramsMap, secretKey);
    }

    private static void initHeaderInfo() {
        if (headerMap != null && headerMap.size() > 0) {
            Iterator iter = headerMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = entry.getKey().toString();
                Object val = entry.getValue();
                asyncHttpClient.addHeader(key, val.toString());
            }
        }
    }

    /**
     * 初始化token主要参数
     *
     * @param userName
     * @param pwd
     * @param token
     */
    public static void initHttpTokenConfig(String userName, String pwd, String token) {
        if (mTokenConfig == null) {
            mTokenConfig = new TokenConfig(BaseApplication.appContext);
        }
        mTokenConfig.setUserName(userName);
        mTokenConfig.setPassword(pwd);
        mTokenConfig.setTime(new Date().getTime());
        mTokenConfig.setToken(token);
    }

    /**
     * 设置token动态失效时间
     *
     * @param tokenOutTime
     */
    public static void setTokenOuttime(Long tokenOutTime) {
        if (mTokenConfig == null) {
            mTokenConfig = new TokenConfig(BaseApplication.appContext);
        }
        mTokenConfig.setTokenTime(tokenOutTime * 1000);
        mTokenConfig.setTime(new Date().getTime());
    }


    private void setUpRequestParams(RequestParams params) {
        params.setContentEncoding(ENCODE);
    }

    public static void httpPost(String url, RequestParams params, CommonHttpResponseHandler handler) {
        logD("POST", url, JsonUtil.toJson(params));
        RequestHandle requestHandle = asyncHttpClient.post(url, params, handler);
        mRequestHandle = requestHandle;
    }

    public static void httpPost(String url, RequestParams params, FileHttpResponseHandler handler) {
        logD("POST", url, JsonUtil.toJson(params));
        RequestHandle requestHandle = asyncHttpClient.post(url, params, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void httpPost(final Context context, final String url, final String requestStr, final HttpResponseHandler<T> handler) {
        try {
            logD("POST", url, requestStr);
            final StringEntity entity = new StringEntity(requestStr, ENCODE);
            RequestHandle requestHandle = asyncHttpClient.post(context, url, entity, CONTENT_TYPE, handler);
            mRequestHandle = requestHandle;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> void httpPost(Context context, String url, String requestStr, CommonHttpResponseHandler handler) {
        StringEntity entity = null;
        try {
            logD("POST", url, requestStr);
            entity = new StringEntity(requestStr, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestHandle requestHandle = asyncHttpClient.post(context, url, entity, CONTENT_TYPE, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void httpPost(Context context, String url, String requestStr, ProwlJsonResponseHttpHandler handler) {
        StringEntity entity = null;
        try {
            logD("POST", url, requestStr);
            entity = new StringEntity(requestStr, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestHandle requestHandle = asyncHttpClient.post(context, url, entity, CONTENT_TYPE, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void httpPost(Context context, String url, String requestStr, JsonResponseHttpHandler<T> handler) {
        StringEntity entity = null;
        try {
            logD("POST", url, requestStr);
            entity = new StringEntity(requestStr, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestHandle requestHandle = asyncHttpClient.post(context, url, entity, CONTENT_TYPE, handler);
        mRequestHandle = requestHandle;
    }

    public static void httpPost(Context context, String url, String requestStr, AsyncHttpResponseHandler handler) {
        StringEntity entity = null;
        try {
            logD("POST", url, requestStr);
            entity = new StringEntity(requestStr, ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestHandle requestHandle = asyncHttpClient.post(context, url, entity, CONTENT_TYPE, handler);
        mRequestHandle = requestHandle;
    }

    public static <T> void get(String url, HttpResponseHandler<T> httpHandler) {
        httpGet(url, null, httpHandler);
    }

    public static void get(String url, AsyncHttpResponseHandler httpHandler) {
        RequestHandle requestHandle = asyncHttpClient.get(url, httpHandler);
        mRequestHandle = requestHandle;
    }

    public static <T> void get(Context context, String url, Map params, HttpResponseHandler<T> httpHandler) {
        String request = null;
        if (params != null) {
            try {
                setAsyncHttpHeaders(params);
                request = JsonUtil.toJson(params);
                httpGet(context, url, request, httpHandler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    public static <T> void get(final String url, final Map params, final JsonResponseHttpHandler<T> httpHandler) {
        if (params != null) {
            httpGet(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    /**
     * @param url
     * @param params
     * @param httpHandler
     * @param <T>
     */
    public static void get(final String url, final Map params, final AsyncHttpResponseHandler httpHandler) {
        if (params != null) {
            httpGet(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    public static void get(final String url, final Map params, double cacheTime,final AsyncHttpResponseHandler httpHandler) {
        if (params != null) {
            Map<String,String> map = new HashMap<>();
            map.putAll(params);map.remove("access_token");
            String paramsStr = JsonUtil.toJson(map);
            if (cacheTime>0){
                String s = HttpCache.getInstance().getUrlDataString(url+paramsStr);
                if (!TextUtils.isEmpty(s)){
                    logD("GET Cache", url, JsonUtil.toJson(params));
                    httpHandler.onSuccess(200,null,s.getBytes());
                    return;
                }
            }
            if (httpHandler instanceof JsonHttpHandler){
                ((JsonHttpHandler)httpHandler).setUrlandTime(url+paramsStr,cacheTime);
            }
            httpGet(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    /**
     * HttpGet请求
     *
     * @param context     通过context是否为空来显示Dialog,context不为空则显示dialog，为空啥都不显示
     * @param url
     * @param params
     * @param httpHandler
     * @param <T>
     */
    public static <T> void getSimple(Context context, final String url, final Map params, final JsonHttpHandler<T> httpHandler) {
        if (context != null) {
            httpHandler.setDialogMsg(context, "正在请求数据...");
        }
        if (params != null) {
            httpGet(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    /**
     * Http的Get请求，不会显示dialog
     *
     * @param url
     * @param params
     * @param httpHandler
     * @param <T>
     */
    public static <T> void getSimple(final String url, final Map params, final JsonHttpHandler<T> httpHandler) {
        getSimple(null, url, params, httpHandler);
    }


    public static <T> void get(final String url, final Map params, final HttpResponseHandler<T> httpHandler) {
        if (params != null) {
            httpGet(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    public static <T> void get(final String url, final Map params, final ProwlJsonResponseHttpHandler<T> handler) {
        if (params != null) {
            httpGet(url, new RequestParams(params), handler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to get function");
        }
    }

    public static <T> void post(final Context context, final String url, final Map params, final HttpResponseHandler<T> httpHandler) {
        if (params != null) {
            String request = JsonUtil.toJson(params);
            httpPost(context, url, request, httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }


    public static <T> void post(final Context context, final String url, final Map params, final JsonResponseHttpHandler<T> httpHandler) {
        if (params != null) {
            String request = JsonUtil.toJson(params);
            httpPost(context, url, request, httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }

    /**
     * Post请求，若需要显示Dialog和提示，请输入msg
     *
     * @param context
     * @param msg             若需要显示dialog，请设置提示信息，若为空，则不显示
     * @param url
     * @param params
     * @param jsonHttpHandler
     * @param <T>
     */
    public static <T> void postSimple(final Context context, String msg, final String url, final Map params, final JsonHttpHandler<T> jsonHttpHandler) {

        if (!TextUtils.isEmpty(msg)) {
            jsonHttpHandler.setDialogMsg(context, msg);
        }
        if (params != null) {
            String request = JsonUtil.toJson(params);
            httpPost(context, url, request, jsonHttpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }

    /**
     * Post请求,该请求不会显示dialog
     *
     * @param context
     * @param url
     * @param params
     * @param jsonHttpHandler
     * @param <T>
     */
    public static <T> void postSimple(final Context context, final String url, final Map params, final JsonHttpHandler<T> jsonHttpHandler) {
        postSimple(context, null, url, params, jsonHttpHandler);
    }


    public static <T> void post(Context context, String url, Object params, JsonResponseHttpHandler<T> httpHandler) {
        String request = null;
        if (params != null) {
            try {
//                setAsyncHttpHeaders(params);
                request = JsonUtil.toJson(params);
                httpPost(context, url, request, httpHandler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }

    public static void post(final Context context, final String url, final Map params, final CommonHttpResponseHandler httpHandler) {
        if (params != null) {
            String request = JsonUtil.toJson(params);
            httpPost(context, url, request, httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }


    public static <T> void post(Context context, String url, List params, ProwlJsonResponseHttpHandler<T> httpHandler) {
        String request = null;
        if (params != null) {
            try {
//                setAsyncHttpHeaders(params);
                request = JsonUtil.toJson(params);
                httpPost(context, url, request, httpHandler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }

    public static void post(final Context context, final String url, final Map params, final ProwlJsonResponseHttpHandler httpHandler) {
        if (params != null) {
            String request = JsonUtil.toJson(params);
            httpPost(context, url, request, httpHandler);
        } else {
            Log.w("HttpUtil", "you should define 'params' to post-function");
        }
    }

    public static void post(final String url, final Map params, final AsyncHttpResponseHandler httpHandler) {
        if (params != null) {
            asyncHttpClient.post(url, new RequestParams(params), httpHandler);
        } else {
            Log.w("HttpUtil", "you should define params to post func");
        }
    }

    public static void post(String url, Map params, FileHttpResponseHandler httpHandler) {
        if (params != null) {
            setAsyncHttpHeaders(params);
            RequestParams request = new RequestParams(params);
            asyncHttpClient.post(url, request, httpHandler);
        } else {
            Log.w("HttpUtil", "you should define params to post func");
        }
    }

    /**
     * 上传单个文件
     *
     * @param <T>
     * @param upUrl
     * @param filePath
     * @param httpHandler
     */
    public static <T> void uploadFile(String upUrl, String filePath, Map map, CommonHttpResponseHandler httpHandler) {

        try {
            File file = new File(filePath);
            if (file.exists()) {
                setAsyncHttpHeaders(map);
                RequestParams params = new RequestParams(map);
                params.put("file", file);
                httpPost(upUrl, params, httpHandler);
            }
        } catch (FileNotFoundException e) {
            Log.e("HttpUtil", "uploadFile", e);
            //// TODO: 2016/3/28 文件不存在的处理 
        }
    }

    public static <T> void uploadFileSync(Context context, String upUrl, String filePath, Map map, CommonHttpResponseHandler httpHandler) {

        try {
            logD("UPLOAD", upUrl, JsonUtil.toJson(map));
            File file = new File(filePath);
            if (file.exists()) {
                setSyncHttpHeaders(map);
                String request = JsonUtil.toJson(map);
                LogUtil.i("----uploadFileSync--->" + request);
                RequestParams params = new RequestParams(map);
                params.put("file", file);
                syncHttpClient.setConnectTimeout(1 * 60 * 1000);
                syncHttpClient.setTimeout(1 * 60 * 1000);
                syncHttpClient.setMaxRetriesAndTimeout(3, 10 * 1000);
                syncHttpClient.setLoggingEnabled(true);
                syncHttpClient.post(context, upUrl, params, httpHandler);
            }
        } catch (Exception e) {
            Log.e("HttpUtil", "uploadFileSync", e);
            //// TODO: 2016/3/28 文件不存在的处理
            httpHandler.onFailure(-2, e.getLocalizedMessage());
        }
    }

    private static void initSycnHttpParams() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String clientVersion = DeviceUtil.getVersionName(BaseApplication.appContext);
        syncHttpClient.setConnectTimeout(CONNECT_OUT_TIME);
        syncHttpClient.setTimeout(CONNECT_OUT_TIME);
        syncHttpClient.addHeader(HEADER_APP_ID, appId + "");
        syncHttpClient.addHeader(HEADER_TIMESTAMP, timestamp);
        syncHttpClient.addHeader(HEADER_CLIENT_TYPE, clientType);
        syncHttpClient.addHeader(HEADER_CLIENT_VER, clientVersion);
//        syncHttpClient.addHeader(HEADER_SIGN, getToken(timestamp,clientType,null));
    }

    /**
     * 非异步请求设置头信息的方法
     *
     * @param params
     */
    private static void setSyncHttpHeaders(Map params) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String clientVersion = DeviceUtil.getVersionName(BaseApplication.appContext);
        syncHttpClient.setConnectTimeout(CONNECT_OUT_TIME);
        syncHttpClient.setTimeout(CONNECT_OUT_TIME);
        syncHttpClient.addHeader(HEADER_APP_ID, appId + "");
        syncHttpClient.addHeader(HEADER_TIMESTAMP, timestamp);
        syncHttpClient.addHeader(HEADER_CLIENT_TYPE, clientType);
        syncHttpClient.addHeader(HEADER_CLIENT_VER, clientVersion);
        syncHttpClient.addHeader(HEADER_SIGN, getToken(timestamp, clientType, params));
    }

    /**
     * 上传多个文件
     *
     * @param upUrl
     * @param filePath
     * @param httpHandler
     */
    public static void uploadFiles(String upUrl, List<String> filePath, FileHttpResponseHandler httpHandler) {
        try {
            RequestParams params = new RequestParams();
            File[] files = new File[filePath.size()];
            for (int i = 0; i < files.length; i++) {
                File file = new File(filePath.get(i));
                if (file.exists()) {
                    files[i] = file;
                }
            }
            params.put("file", files);
            httpPost(upUrl, params, httpHandler);
        } catch (FileNotFoundException e) {
            Log.e("HttpUtil", "uploadFiles", e);
        }
    }

    /**
     * 简单下载文件
     *
     * @param url
     * @param httpHandler
     */
    public static void download(String url, String fileName, FileHttpResponseHandler httpHandler) {
        if (httpHandler == null) {
            throw new RuntimeException("http handler cannot be null");
        }
        try {
            asyncHttpClient.get(url, httpHandler);
        } catch (Exception e) {
            Log.e("HttpUtil", "download", e);
            //// TODO: 2016/3/28 文件不存在的处理
        }
    }

    public static void download(String url, FileAsyncHttpResponseHandler httpHandler) {
        if (httpHandler == null) {
            throw new RuntimeException("http handler cannot be null");
        }
        try {
            asyncHttpClient.get(url, httpHandler);
        } catch (Exception e) {
            Log.e("HttpUtil", "download", e);
            //// TODO: 2016/3/28 文件不存在的处理
        }
    }

    public static void cancelRequest(Context context) {
        asyncHttpClient.cancelRequests(context, true);
    }

    /**
     * 只会取消最后一次请求
     */
    public static void cancelRequest() {
        if (mRequestHandle != null) {
            mRequestHandle.cancel(true);
        }
    }

    public static void logD(String type, String content) {
        logD(type, null, content);
    }

    public static void logD(String type, String url, String content) {
        if (ENABLE_LOG) {
            if (url != null) {
                LogUtil.d("[HttpUtil][" + type + "] [url=" + url + "] [request=" + content + "]");
            } else {
                LogUtil.d("[HttpUtil][" + type + "]request=" + content);
            }
        }
    }

}
